import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Card, Collapse, Spin, message} from 'antd';
import routes from './routes';
import {FORM_BIG_OPTIONS, PAGE} from '../constants';
import {PERMISSION} from './constants';
import styles from './style.css';
import FileUpload from './FileUpload';
import Return from '../common/Return';
import CommonDetail from './CommonDetail';
import ImagePreviewBtn from '../common/ImagePreviewBtn';
const Panel = Collapse.Panel;
const EMPTY_ARRAY = [];
const bodyStyle = {
    padding: 0
};
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updateAttachments(data);
    }

    onChangeRemove= data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.removeAttachments(data);
    }

    onSubmit = () => {
        const {attachments = []} = this.props.conditions;
        if(!attachments.length)
            return Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.onSubmit.title',
                    defaultMessage: '附件清单为空，是否继续提交'
                }),
                onOk: () => {
                    this.setState({
                        loading: true
                    });
                    this.props.onSubmit().then(success => {
                        if(this.ismounted && !success)
                            this.setState({
                                loading: false
                            });
                    });
                }
            });
        this.setState({
            loading: true
        });
        return this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    
    render() {
        const {attachments = []} = this.props.conditions;
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card bodyStyle={bodyStyle}>
                            <Collapse defaultActiveKey="1" bordered={false}>
                                <Panel header={this.props.intl.formatMessage({
                                    id: 'add.detail.panel',
                                    defaultMessage: '发票信息'
                                })} key="1" forceRender>
                                    <CommonDetail
                                        showBrand={this.props.showBrand}
                                        isDealerUser={this.props.isDealerUser}
                                        detail={this.props.conditions} />
                                </Panel>
                            </Collapse>
                        </Card>
                        <Card
                            extra={<ImagePreviewBtn attachments={attachments} />}
                            title={this.props.intl.formatMessage({
                                id: 'add.card.fileList.title',
                                defaultMessage: '附件清单'
                            })}>
                            <Row>
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload} onRemove={this.onChangeRemove} fileList={attachments} />
                                </Col>
                            </Row>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    removeAttachments: PropTypes.func.isRequired,
    submitable: PropTypes.bool.isRequired,
    updateAttachments: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    showBrand: PropTypes.bool
};
import {connect} from 'react-redux';
import {
    clearData,
    tableSearch,
    onClickConfirm,
    updateAttachments,
    removeAttachments,
    getEditInit,
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.confirm) && options.includes(PERMISSION.confirm);
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    conditions: getSubmitData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    showBrand: state.getIn(['page', 'domainData', 'brands', 'data']).size > 1
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onSubmit: () =>
        dispatch(onClickConfirm(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    updateAttachments: data => dispatch(updateAttachments(data)),
    removeAttachments: ({id}) => dispatch(removeAttachments(id)),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
